/*
 * Copyright (C) 2018 guomw.Inc. All rights reserved.
 * 项目名称： report-manage
 * 文件名称： StringHelper.java
 * Date：18-11-5 上午10:54
 * Author: guomw
 */

package com.guomw.report.common.utils;

import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author guomw
 * @date 2018/10/16
 */
public class StringHelper {

    /**
     * 获取当前网络ip
     *
     * @param request
     * @return
     */
    public static String getClientIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Real-IP");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) {
            //"***.***.***.***".length() = 15
            if (ipAddress.indexOf(",") > 0) {
                ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

    /**
     * 获取安全手机，手机中间4位打*
     * @param var
     * @return
     */
    public static  String safeGetMobile(String var){
        if (checkMobile(var)){
            String phoneNumber = var.replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
            return phoneNumber;
        }
        return var;
    }

    /**
     * 校验手机号码格式
     * 格式为1[3-9]********* 11位数字
     * @param mobile
     * @return
     */
    public static boolean checkMobile(String mobile){
        String regex = "^(1[3-9])\\d{9}$";
        return check(mobile, regex);
    }

    /**
     * 正则校验
     * @param str
     * @param regex
     * @return
     */
    public static boolean check(String str, String regex) {
        boolean flag;
        try {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(str);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

}
